package ai.tasks;

import misc.Debug;
import ai.AIConstant;
import ai.Trackable;
import ai.PathFinding;
import ai.AIUtil;
import ai.engine.AIPlayer;
import ai.engine.AIResource;
import ai.engine.AIUnit;
import ai.engine.Task;
import ai.engine.TaskDoer;
import ai.engine.factories.TaskFactory;
import engine.GameEngine;
import engine.UnitAction;
import engine.data.Unit;
import engine.data.UnitType;
import util.ArrayList;
import util.List;

public class AttackUnitTask extends Task {

	public AttackUnitTask(short id, Trackable target) {
		super(id, TaskFactory.ATTACK_UNIT_TASK, AIUnit.class, "Attack Unit", "",
				AIConstant.PRIORITY_STRONG, target, AIUtil.getCurrentAIP().attackMin,
		AIUtil.getCurrentAIP().attackMax);
	}

	public Unit getTarget() {
		return (Unit) target;
	}

	public boolean isTaskSuitable(TaskDoer possibleTaskDoer) {
		AIUnit possibleUnitDoer = (AIUnit) possibleTaskDoer;
		return UnitType.getAP(possibleUnitDoer.type) > 0;
	}

	public short getFormula(TaskDoer possibleTaskDoer) {
		AIUnit possibleUnitDoer = (AIUnit) possibleTaskDoer;
		if (this.target == null)
			Debug.logConsole("Warning : Target cannot be null in " + this);
		if (possibleUnitDoer == null)
			Debug.logConsole("Warning : possibleTaskDoer cannot be null in "
					+ this);

		return (short) (this.priority + (((AIPlayer)GameEngine.currPlayer).getAIP().aggresive
				- UnitType.getDP(this.getTarget().type) + UnitType
				.getAP(possibleUnitDoer.type)));
	}

	public byte getAction(TaskDoer taskDoer) {
		AIUnit unitDoer = (AIUnit) taskDoer;
		if (!this.getAssignedResources().contains(taskDoer))
			return UnitAction.SKIP;
		// Trouver le chemin et avancer d'un pas dans le chemin.
		short[] lastSeenPosition = ((Unit) target)
				.getLastSeenPosition(GameEngine.currPlayer);
		Debug.logConsole("Attack " + PathFinding.getNextDirection(PathFinding.TYPE_QUICKEST,
				unitDoer, lastSeenPosition));
		return PathFinding.getNextDirection(PathFinding.TYPE_QUICKEST,
				unitDoer, lastSeenPosition);
	}

	public List getAdditionalResourcesNeeded() {
		List resourcesNeeded = new ArrayList();
		AIResource resource; 
		for (int i = this.getAssignedResources().size(); i < this.resourcesMin; i++) {
			resource = new AIResource(getTarget(), AIUtil.getBestAttackUnitType());		
			resourcesNeeded.add(resource);
		}
		return resourcesNeeded;
	}

	public boolean isObjectiveAchieved() {
		short[] lastSeenPosition = this.getTarget().getLastSeenPosition(
				GameEngine.currPlayer);
		if (GameEngine.map.isSeen(GameEngine.currPlayer, lastSeenPosition[0],
				lastSeenPosition[1])) {
			if (!AIUtil.isOnSameTile(lastSeenPosition, getTarget())) {
				AIUtil.getCurrentAIPlayer().enemyUnits.remove(target);
				return true;
			}
		}

		if (!this.getTarget().player.units.contains(target)) {
			AIUtil.getCurrentAIPlayer().enemyUnits.remove(target);
			return true;
			// Retourne
		}
		return false;
	}

}
